//
//  APPTools.m
//  TableView&CollectionView
//
//  Created by 何欣 on 15/12/18.
//  Copyright © 2015年 何欣. All rights reserved.
//

#import "APPTools.h"
#import "AFNetworking.h"
#import "AFNetworkReachabilityManager.h"
#import <UIKit/UIKit.h>


@implementation APPTools

+ (void)GETWithURL:(NSString *)urlStr
               par:(NSDictionary *)dic
           success:(void (^)(id))responseObj filed:(void (^)(NSError *))err
{
    
    // 获取AFN网络请求的manager
    AFNetworkReachabilityManager *netWorkManger = [AFNetworkReachabilityManager sharedManager];
    
    // 如果要检测网络状态的变化，必须用检测管理器的单例的startMonitoring
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    // 获取沙盒路径
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    // 文件管理器
    NSFileManager *manger = [NSFileManager defaultManager];
    
    // 使用文件管理器创建一个文件夹
    // 拼接文件夹路径
    NSString *byjCaches = [documentPath stringByAppendingPathComponent:@"BYJCaches"];
    NSLog(@"%@", byjCaches);
    
    BOOL result = [manger createDirectoryAtPath:byjCaches withIntermediateDirectories:YES attributes:nil error:nil];
    
    if (result) {
       // NSLog(@"创建缓存的文件夹成功");
    } else {
       // NSLog(@"创建缓存的文件夹失败");
    }
    
    // 拼接缓存的路径
    NSString *path = [NSString stringWithFormat:@"%ld.plist", [urlStr hash]];
    
    // 将这个缓存写在自己创建的文件夹下面
    NSString *textFilePath = [byjCaches stringByAppendingPathComponent:path];
    
    // 检测网络连接的单利，网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
    }];
    
    
    NSString *str = [NSString stringWithFormat:@"%@", urlStr];
    

    AFHTTPSessionManager *man = [AFHTTPSessionManager manager];
    // 有的返回的数据格式，AFN不支持解析，所以我们要设置一下。让AFN支持。
    [man.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
    
    str = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    [man GET:str parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [netWorkManger stopMonitoring];
        
        responseObj(responseObject);
        
        //BOOL result = [responseObject writeToFile:textFilePath atomically:YES];
        
        BOOL result = [NSKeyedArchiver archiveRootObject:responseObject toFile:textFilePath];
        
        if (result) {
        //    NSLog(@"写入成功");
        } else {
            NSLog(@"写入失败");
        }
        
        //NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithContentsOfFile:textFilePath];
       // NSLog(@"%@", dic);
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        err(error);
        
        //id dic = [NSMutableDictionary dictionaryWithContentsOfFile:textFilePath];
       // responseObj(dic);
       // err(dic);
        NSDictionary *result = [NSKeyedUnarchiver unarchiveObjectWithFile:textFilePath];
        
        responseObj(result);
        
        //NSLog(@"%@", dic);

    }];
}

+ (void)POSTWithURL:(NSString *)urlStr
                par:(NSDictionary *)dic
            success:(void (^)(id))response filed:(void (^)(NSError *))err
{
    

    // 1. 获取AFN网络请求的Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //    // 1. 获取AFN网络请求的Manager
    //    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    AFNetworkReachabilityManager *netWorkManger = [AFNetworkReachabilityManager sharedManager];
    
    // 如果要监测网络状态的变化,必须用检测管理器的单例的startMonitoring
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    // 获取沙盒路径
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    // 文件管理器
    NSFileManager *manger = [NSFileManager defaultManager];
    // 使用文件管理器创建一个文件夹
    // 拼文件夹路径
    NSString *totoroCaches = [documentPath stringByAppendingPathComponent:@"BYJCaches"];
    
    BOOL resultFile = [manger createDirectoryAtPath:totoroCaches withIntermediateDirectories:YES attributes:nil error:nil];
    if (resultFile) {
        NSLog(@"创建缓存的文件夹成功");
    } else {
        NSLog(@"创建存缓存的文件夹失败");
    }
    // 拼接缓存路径
    NSString *path = [NSString stringWithFormat:@"%ld.plist",[urlStr hash]];
    // 将这个缓存写在自己创建的文件夹下面
    NSString *textFilPath = [totoroCaches
                             stringByAppendingPathComponent:path];
    
    // 检测网络连接的单例,网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        //        NSLog(@"网络状态 = %ld",status);
    }];
    
    NSString *str = [NSString stringWithFormat:@"%@",urlStr];
    
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
    
    str = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    [manager POST:str parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [netWorkManger stopMonitoring];
        response(responseObject);
        
       // BOOL result = [responseObject writeToFile:textFilPath atomically:YES];
        
        BOOL result = [NSKeyedArchiver archiveRootObject:responseObject toFile:textFilPath];
        
        if (result) {
            NSLog(@"写入成功");
        }else{
            
            NSLog(@"写入失败");
        }
        //        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithContentsOfFile:textFilPath];
        //        NSLog(@"%@",dic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        err(error);
        
        id result = [NSMutableDictionary dictionaryWithContentsOfFile:textFilPath];
       // NSDictionary *result = [NSKeyedUnarchiver unarchiveObjectWithFile:textFilPath];
        
        response(result);
        
    }];
 
}

+ (CGSize)labelRectWithSize:(CGSize)size labelText:(NSString *)labelText Font:(UIFont *)font {
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
    
    CGSize actualsize = [labelText boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    
    return actualsize;
}


@end
